<template>
    <div class="container">
        <!-- 导航栏区域开始 -->
        <TridentNavBar>
            <template #left><i class="iconfont icon-zuojiantou"></i></template>
            <template #default>聊天记录</template>
        </TridentNavBar>
        <!-- 导航栏区域结束 -->

        <!-- 过滤区域开始 -->
        <div class="filter-wrap">
            <van-dropdown-menu active-color="#27BA9B">
                <!-- 类型 -->
                <van-dropdown-item @change="handleFilterMessage" v-model="messageListParams.type" :options="messagetypes" />
                
                <!-- 排序 -->
                <van-dropdown-item @change="handleSortMessage" v-model="messageListParams.sort_type" :options="sortTypes" />

                <!-- 日期筛选 -->
                <van-dropdown-item @open="handleOpenDateDropdown" title="日期筛选" ref="dateFilterRef">
                    <van-cell-group inset>
                        <van-field
                            v-model="messageListParams.start_create_time"
                            label="开始日期"
                            left-icon="notes-o"
                            placeholder="日期格式:0000-00-00"
                            :focus="true"
                            @focus="handleShowDate($event, 1)"
                            :readonly="true"
                        />
                        <van-field
                            v-model="messageListParams.end_create_time"
                            clearable
                            label="结束日期"
                            left-icon="notes-o"
                            placeholder="日期格式:0000-00-00"
                            @focus="handleShowDate($event, 2)"
                            :readonly="true"
                        />
                    </van-cell-group>

                    <div class="date-filter-btn-box">
                        <van-button style="margin-right: 15px;" color="#bbb" @click="handleReset">重 置</van-button>

                        <van-button color="#27BA9B" type="primary" @click="handleConfirm">确 认</van-button>
                    </div>

                    <!-- 选择日期区域 -->
                    <div class="date-box">
                        <van-date-picker
                            v-show="isShowDatePicker"
                            title="选择日期"
                            :min-date="minDate"
                            :max-date="maxDate"
                            @confirm="handleConfirmDate"
                            @cancel="handleCancelDate"
                        />
                    </div>
                </van-dropdown-item>
            </van-dropdown-menu>
        </div>
        <!-- 过滤区域结束 -->


        <!-- 列表区域开始 -->
        <div class="content-wrap">
            <van-pull-refresh
                v-model="refreshing"
                @refresh="onRefresh"
                style="min-height: calc(100vh - 100px);"
            >
                <van-list
                    v-model:loading="loading"
                    :finished="finished"
                    :finished-text="totalPage > 1 ? '没有更多了' : ''"
                    @load="getMessageList"
                    offset="50"
                    class="list-wrap"
                >
                    <!-- 骨架屏区域 -->
                    <div class="skeleton-item" v-for="(index) in 6" :key="index" v-if="isSkeleton">
                        <van-skeleton>
                            <template #template>
                                <div class="skeleton-box">
                                    <div class="title">
                                        <van-skeleton-paragraph style="width: 30px;height: 30px;border-radius: 15px;margin-right: 5px;"/>
                                        <van-skeleton-paragraph row-width="20%" />
                                    </div>

                                    <div class="content">
                                        <van-skeleton-paragraph row-width="100%" />
                                        <van-skeleton-paragraph row-width="100%" style="margin: 5px 0;"/>
                                        <van-skeleton-paragraph row-width="100%" />
                                    </div>
                                    <div class="footer">
                                        <van-skeleton-paragraph row-width="36%" />
                                    </div>
                                </div>
                            </template>
                        </van-skeleton>
                    </div>

                    <template v-if="messageList.length > 0">
                        <div class="record-item" v-for="(item, index) in messageList" :key="index">
                            <div class="title-box">
                                <van-image
                                    round
                                    width="30"
                                    height="30"
                                    fit="cover"
                                    :src="item.from_user?.avatar_url ? global.MINIO_FILE_DOMAIN + item.from_user?.avatar_url : 'src/assets/images/default_avatar.png'"
                                />
                                <div class="username">{{ item.from_user?.username }}</div>
                            </div>
                            <div class="content">
                                <div class="text" v-if="item.type == 1">{{ item.contents }}</div>
                                <div class="image" v-else-if="item.type == 2">
                                    <van-image
                                        width="80"
                                        height="80"
                                        fit="contain"
                                        :src="global.MINIO_FILE_DOMAIN + item.image_url"
                                        @click="handleShowImagePreview(global.MINIO_FILE_DOMAIN + item.image_url)"
                                    />
                                </div>
                            </div>
                            <div class="time">{{ item.create_time }}</div>
                        </div>
                    </template>
                    <template v-else>
                        <TridentEmpty v-if="!loading" />
                    </template>

                    <!-- 返回顶部 -->
                    <van-back-top bottom="100" right="10"><i class="iconfont icon-top" style="font-size: 30px;"></i></van-back-top>
                </van-list>
            </van-pull-refresh>
        </div>
        <!-- 列表区域结束 -->
    </div>
</template>

<script lang="ts" setup>
import { reqMessageListAPI } from '@/apis/message'
import { useUserStore } from '@/store/modules/user'
import type { Message, MessageListParam } from '@/types/chat'
import { showImagePreview, showToast } from 'vant'
import { inject, nextTick, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'


// ----------------- 定义全局变量开始 -----------------
// 全局属性
const global: any = inject('global')

// 路由
const route = useRoute()

// 用户存储
const userStore = useUserStore()

// 骨架屏
const isSkeleton = ref<boolean>(false)
// ----------------- 定义全局变量结束 -----------------



// --------------- 处理日期筛选功能开始 ---------------
// 日期过滤Ref
const dateFilterRef = ref()

// 是否显示日期选择器
const isShowDatePicker = ref<boolean>(false)

// 日期模式：1-开始,2-结束
const dateMode = ref<number>(1)

// 最小日期
const minDate = ref(new Date(2020, 0, 1))

// 最大日期
const maxDate = ref(new Date(2025, 5, 1))

// 处理打开日期下拉菜单
const handleOpenDateDropdown = () => {
    // messageListParams.start_create_time = startCreateTime.value.join('-')
}

// 处理显示日期
const handleShowDate = (e: any, mode: number) => {
    dateMode.value = mode
    isShowDatePicker.value = !isShowDatePicker.value
}

// 处理确认日期
const handleConfirmDate = (date: any) => {
    if (dateMode.value == 1) { // 开始日期
        messageListParams.start_create_time = date.selectedValues.join('-')
    } else { // 结束日期
        messageListParams.end_create_time = date.selectedValues.join('-')
    }
    
    isShowDatePicker.value = false
}

// 处理取消日期
const handleCancelDate = () => {
    isShowDatePicker.value = false
}

// 处理重置
const handleReset = async () => {
    messageListParams.start_create_time = ''
    messageListParams.end_create_time = ''
}

// 处理确认
const handleConfirm = async () => {
    // 判断时间
    if (messageListParams.start_create_time && messageListParams.end_create_time) {
        if (messageListParams.start_create_time > messageListParams.end_create_time) {
            showToast('开始日期不能大于结束日期!')
            return false
        }
    }

    dateFilterRef.value.toggle()

    messageList.value = []
    messageListParams.page = 1

    // 当加载完成设置为false,将会自动调用getMessageList()方法获取数据
    // 但是第一页数据需要手动getMessageList()
    finished.value = false

    // 当获取第一页数据的时候需要手动调用接口
    // 非第一页数据则无需手动调用接口,会自动调用接口
    if (messageListParams.page == 1) {
        await getMessageList()
    }
}
// --------------- 处理日期筛选功能结束 ---------------



// ----------------- 处理筛选功能开始 -----------------
// 消息类型
const messagetypes = ref([
    {
        text: '全部',
        value: 0
    },
    {
        text: '文本',
        value: 1
    },
    {
        text: '图片',
        value: 2
    },
    {
        text: '语音',
        value: 3
    },
    {
        text: '视频',
        value: 4
    },
    {
        text: '位置',
        value: 5
    }
])

// 排序类型
const sortTypes = ref([
    {
        text: '时间倒序',
        value: 'desc'
    },
    {
        text: '时间升序',
        value: 'asc'
    }
])

// 过滤消息类型
const handleFilterMessage = async (value: any) => {
    messageList.value = []
    messageListParams.page = 1
    messageListParams.type = value

    // 当加载完成设置为false,将会自动调用getMessageList()方法获取数据
    // 但是第一页数据需要手动getMessageList()
    finished.value = false

    // 当获取第一页数据的时候需要手动调用接口
    // 非第一页数据则无需手动调用接口,会自动调用接口
    if (messageListParams.page == 1) {
        await getMessageList()
    }
}

// 消息排序
const handleSortMessage = async (value: any) => {
    messageList.value = []
    messageListParams.page = 1
    messageListParams.sort_type = value

    // 当加载完成设置为false,将会自动调用getMessageList()方法获取数据
    // 但是第一页数据需要手动getMessageList()
    finished.value = false

    // 当获取第一页数据的时候需要手动调用接口
    // 非第一页数据则无需手动调用接口,会自动调用接口
    if (messageListParams.page == 1) {
        await getMessageList()
    }
}
// ----------------- 处理筛选功能结束 -----------------



// ----------------- 下拉刷新功能开始 -----------------
const refreshing = ref<boolean>(false)
const onRefresh = async () => {
    // 清空列表数据
    finished.value = false

    // 将 loading 设置为 true，表示处于加载状态
    loading.value = true

    messageListParams.page = 1

    await getMessageList()
}
// ----------------- 下拉刷新功能结束 -----------------



// ---------------- 处理消息列表功能开始 ----------------
const loading = ref(false)

// 完成
const finished = ref(false)

// 消息列表参数
const messageListParams = reactive<MessageListParam>({
    from_uid: route.query.mode == '1' ? userStore.profile.user.uid : 0,
    to_uid: route.query.to_uid as never,
    is_dialogue: route.query.mode == '1' ? 1 : 0,
    mode: route.query.mode as never,
    type: 0,
    page: 1,
    page_size: 10,
    sort_field: 'create_time',
    sort_type: 'desc',
    start_create_time: '',
    end_create_time: ''
})

// 消息列表
const messageList = ref<Message[]>([])

// 总条数
const total = ref<number>(0)

// 总页数
const totalPage = ref<number>(0)

// 获取消息列表
const getMessageList = async () => {
    isSkeleton.value = true
    if (refreshing.value) {
        messageList.value = []
        refreshing.value = false
    }

    loading.value = true

    const result = await reqMessageListAPI(messageListParams)
    messageList.value.push(...result.data.messages)
    total.value = result.data.total
    totalPage.value = result.data.total_page
    
    if (messageListParams.page < result.data.total_page) {
        messageListParams.page++
    } else {
        finished.value = true
    }

    loading.value = false
    isSkeleton.value = false
}
// ---------------- 处理消息列表功能结束 ----------------



// ------------------ 处理图片预览开始 ------------------
const handleShowImagePreview = (image_url: string) => {
    showImagePreview({images: [image_url], closeable: true});
}
// ------------------ 处理图片预览结束 ------------------
</script>

<style scoped lang="scss">
::v-deep(.van-picker__confirm) {
    color: #27BA9B !important;
}

::v-deep(.van-skeleton) {
    padding: 0px 0px;
}
page,
.container {
    height: 100%;
    // 过滤区域开始
    .filter-wrap {
        position: fixed;
        top: 45px;
        left: 0;
        width: 100%;
        z-index: 100;
        .date-filter-btn-box {
            display: flex;
            justify-content: flex-end;
            margin: 10px 0;
            padding-top: 10px;
            border-top: 1px solid #eaeaea;
            padding-right: 20px;
        }
        .date-box {
            border-top: 1px solid #eaeaea;
            padding-top: 20px;
        }
    }
    // 过滤区域结束

    // 列表区域开始
    .content-wrap {
        padding-top: 100px;
        .list-wrap {
            padding: 0 10px;
            margin-bottom: 10px;
            .record-item {
                background-color: #fff;
                padding: 15px;
                border-radius: 10px;
                margin-top: 5px;
                .title-box {
                    display: flex;
                    align-items: center;
                    padding-bottom: 6px;
                    border-bottom: 1px solid #f1f1f1;
                    .username {
                        font-size: 14px;
                        color: #acabab;
                        margin-left: 5px;
                    }
                }
                .content {
                    line-height: 22px;
                    font-size: 16px;
                    padding-top: 6px;
                    .image {
                        width: 85px;
                        height: 85px;
                        border: 1px solid #efeeee;
                        display: flex;
                        align-content: center;
                        justify-content: center;
                        border-radius: 5px;
                        overflow: hidden;
                    }
                }
                .time {
                    display: flex;
                    justify-content: flex-end;
                    padding-top: 10px;
                    font-size: 14px;
                    color: #acabab;
                }
            }

            .skeleton-item {
                background-color: #fff;
                border-radius: 10px;
                margin-top: 5px;
                .skeleton-box {
                    padding: 15px;
                    width: 100%;
                    .title {
                        display: flex;
                        align-items: center;
                        padding-bottom: 6px;
                    }

                    .content {
                        border-top: 1px solid #f1f1f1;
                        padding-top: 10px;
                    }
                    .footer {
                        padding-top: 10px;
                        display: flex;
                        justify-content: flex-end;
                    }
                }
            }
        }
    }
}
</style>